package com.example.baselib.utils

import android.widget.Button
import com.jakewharton.rxbinding2.view.RxView
import com.jakewharton.rxbinding2.widget.RxTextView
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.functions.Consumer
import java.util.concurrent.TimeUnit

/**
 * @auther XuDan on 2020/9/21.
 */
object RxBindingUtil {
    fun Et(mBt: Button, time: Long) {
        var verifyCodeObservable: Observable<Boolean> = RxView.clicks(mBt)
            .throttleFirst(
                time,
                TimeUnit.SECONDS
            ) //防止20秒内连续点击,或者只使用doOnNext部分
            .subscribeOn(AndroidSchedulers.mainThread())
            .map { o: Any? -> false }
            .doOnNext { enabled: Boolean ->
                mBt.setEnabled(
                    enabled
                )
            }
        verifyCodeObservable.subscribe(Consumer { s: Boolean? ->
            Observable.interval(
                1,
                TimeUnit.SECONDS,
                AndroidSchedulers.mainThread()
            )
                .take(time)
                .subscribe(
                    { aLong: Long ->
                        RxTextView.text(
                            mBt
                        )
                            .accept("剩余" + (time - aLong) + "秒")
                    }
                    ,
                    { obj: Throwable -> obj.printStackTrace() }
                ) {
                    RxTextView.text(mBt).accept("获取验证码")
                    RxView.enabled(mBt).accept(true)
                }
        })
//在destory时，调用，防止泄露
//        verifyCodeObservable.unsubscribeOn(AndroidSchedulers.mainThread())

    }
}